package com.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.exception.BusinessException;
import com.study.exception.ErrorCode;
import com.study.model.dto.task.TaskAddRequest;
import com.study.model.dto.task.TaskQueryRequest;
import com.study.model.dto.task.TaskUpdateRequest;
import com.study.model.entity.Post;
import com.study.model.entity.Task;
import com.study.model.vo.PostVO;
import com.study.model.vo.UserLoginVO;
import com.study.service.TaskService;
import com.study.mapper.TaskMapper;
import com.study.service.UserService;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
* @description 针对表【task(计划表)】的数据库操作Service实现
*/
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task>
    implements TaskService {

    @Autowired
    private UserService userService;
    /***
     * 创建计划
     * @param taskAddRequest
     * @param request
     * @return
     */
    @Override
    public Long createTask(TaskAddRequest taskAddRequest, HttpServletRequest request) {
        if (taskAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Task task = new Task();
        BeanUtils.copyProperties(taskAddRequest, task);
        task.setUserId(userService.getLoginUser(request).getId());
        boolean save = this.save(task);
        if (!save) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "创建失败");
        }
        return task.getId();
    }

    /**
     * 更新计划
     *
     * @param taskUpdateRequest
     * @return
     */
    @Override
    public Boolean updateTask(TaskUpdateRequest taskUpdateRequest) {
        if (taskUpdateRequest == null || taskUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Task task = this.baseMapper.selectById(taskUpdateRequest.getId());
        BeanUtils.copyProperties(taskUpdateRequest, task);
        return this.updateById(task);
    }

    /**
     * 查询用户计划
     *
     * @param request
     * @return
     */
    @Override
    public List<Task> listTaskByUserId(HttpServletRequest request) {
        UserLoginVO user = userService.getLoginUser(request);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        List<Task> taskList = this.baseMapper.selectList(new QueryWrapper<Task>().eq("userId", user.getId()).eq("isDelete", 0));
        return taskList;
    }
}




